package xyz.keyon.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Keyon
 * @explain 第一个过滤器
 * @creat time 2019/10/30 14:55
 */
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("myFirstFilter init");
        System.out.println(filterConfig.getFilterName());
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("拦截到请求");

        //对请求request进行处理
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String username = (String) req.getSession().getAttribute("username");

        if(username == null || username.equals("")){ //满足过滤要求，进行处理
                System.out.println("过滤器检测到用户未登录，返回index.jsp");
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
                return;
        }
        System.out.println("过滤器检测到用户 " + username + " 已登录，不做强制处理");
        filterChain.doFilter(servletRequest, servletResponse); //传递给下一个过滤器或相应Servlet
        System.out.println("拦截到响应");
    }

    @Override
    public void destroy() {
        System.out.println("myFirstFilter destroyed");
    }
}
